/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.struts;

import com.myapp.beans.CreateQuestion;
import com.myapp.beans.Helper;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.w3c.dom.Document;

/**
 *
 * @author Vinh_Dragon
 */
public class CreateQuestionAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        CreateQuestion formbean = (CreateQuestion) form;

        String question = "", answer1 = "", answer2 = "", answer3 = "", answer4 = "", answer5 = "";
        question = formbean.getQuestion();
        answer1 = formbean.getAnswer1();
        answer2 = formbean.getAnswer2();
        answer3 = formbean.getAnswer3();
        answer4 = formbean.getAnswer4();
        answer5 = formbean.getAnswer5();

        ArrayList<String> aslist = new ArrayList<String>();
        aslist.add(answer1);
        aslist.add(answer2);
        aslist.add(answer3);
        aslist.add(answer4);
        aslist.add(answer5);

        Helper help = new Helper();
        String path = this.getServlet().getServletContext().getRealPath("/")+"questions.xml";
        Document doc = help.getDocument(path);
        int id = 0;
        
        for (int i = 0; i < doc.getDocumentElement().getChildNodes().getLength(); i++) {
            if (doc.getDocumentElement().getChildNodes().item(i).getNodeName().equalsIgnoreCase("question")) {
                id++;
            }
        }
        
        help.createElement(doc, String.valueOf(id + 1), question, aslist, path);

        return mapping.findForward(SUCCESS);
    }
}
